<template>
  <view>
    <view class="bg-white">
      <view class="media-box">
        <video
          v-if="currentVideoUrl && currentCourse.fileType === '8'"
          id="myVideo"
          class="video"
          :src="encodeURI(currentVideoUrl)"
          :initial-time="media_init_duration"
          @error="videoErrorCallback"
          @timeupdate="handleTime"
          @play="handlePlay"
          @pause="handlePause"
          @ended="handleEnded"
          controls
        />
      </view>
    </view>
    <view class="bg-white mt-10">
      <view
        v-for="(item, index) in detailData.coursewareLists"
        :key="index"
        class="py-40 px-30 w-full box-content flex"
        @click="handleChangeCourse(item)"
        :class="{ 'bg-studying': isCurrentSelect(item) }"
      >
        <image :src="formatStatus(item.coursewareStatus, 'icon')" />
        <view class="info ml-20">
          <view class="title text-bold">{{ item.coursewareName }}</view>
          <view class="time text-gray">教师：{{ item.teacherName }}</view>
          <view class="time text-gray"
          >总时长：{{ item.learningDurationLabel }}</view
          >
          <view class="time text-gray"
          >已学：{{ item.trainLearnedDurationLabel }}</view
          >
          <text
            :class="[
              'status',
              formatStatus(item.coursewareStatus, 'className'),
            ]"
          >
            {{ formatStatus(item.coursewareStatus, "text") }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { get, find } from "lodash";
import {
  postCourseLearnedTime,
  getTrainingCourse,
} from "@/api/educational-training/trainingTasks";
import config from '@/config'

const statusMap = {
  1: {
    text: "未开始",
    icon: "/static/images/training-tasks/not-started.png",
    className: "color-BBBBBB",
  },
  2: {
    text: "学习中",
    icon: "/static/images/training-tasks/learning.png",
    className: "color-C4C088",
  },
  3: {
    text: "已完成",
    icon: "/static/images/training-tasks/complete.png",
    className: "color-88B4C4",
  },
};
export default {
  components: {
  },
  data() {
    return {
      dialogVisible: false,
      planId: 0,
      media_real_duration: 0,
      media_max_duration: 0,
      media_init_duration: 0,
      media_stop_duration: 0,
      timer: 0,
      detailData: {
        coursewareLists: [],
      },
      currentCourse: {},
      currentDuration: 0,
      currentTime: 0,
      title: "",
      timeCountTimer: null,
      timeCount: 0,
    };
  },
  onLoad({ trainPlanId, pageName }) {
    this.planId = trainPlanId;
    this.title = pageName;
    this.fetchData();
  },
  onHide() {
    // this.saveDuration(2, this.media_max_duration)
    if (this.currentCourse.fileType === "8") {
      const videoContext = uni.createVideoContext("myVideo");
      videoContext.pause();
      this.saveTime();
    }
    clearInterval(this.timer);
  },
  onUnload() {
    // this.saveDuration(2, this.media_max_duration,false)
    this.saveTime();
    clearInterval(this.timer);
  },
  onShow() {
    if (this.currentCourse.fileType === "8") {
      this.dialogVisible = false;
    }
  },
  computed: {
    currentPercent() {
      if (!this.currentDuration) return 0;
      const percent = (this.media_max_duration / this.currentDuration) * 100;
      return Math.floor(percent);
    },
    currentVideoUrl() {
      let url = get(this.currentCourse, "fileUrl", "");
      return url ? `${config.staticUrl}${url}` : '';
    },
  },
  methods: {
    // async saveDuration(status, learningDuration, hasRequest = true) {
    // 	if (!this.isNoComplete(this.currentCourse)) return;
    // 	await postCourseLearnedTime({
    // 		coursewareId: get(this.currentCourse, 'coursewareId', ''),
    // 		learnedDuration: learningDuration,
    // 		coursewareStatus: status,
    // 		trainingPlanId: this.planId,
    // 	});
    // 	hasRequest && this.fetchData();
    // },
    fetchData() {
      return getTrainingCourse(this.planId).then((res) => {
        res.data.coursewareLists = res.data.coursewareList
        this.detailData = res.data;
        this.initCourse();
        this.initTimeAttr();
        uni.setNavigationBarTitle({
          title: this.title,
        });

        // 对第一条数据初始化为学习中
        if (this.detailData.coursewareLists[0].coursewareStatus == "1") {
          this.detailData.coursewareLists[0].coursewareStatus = "2";
          this.saveTime();
        }
      });
    },
    initTimeAttr() {
      this.currentDuration = Number(
        get(this.currentCourse, "learningDuration", 0)
      );
      this.media_init_duration = Number(
        get(this.currentCourse, "trainLearnedDuration", 0)
      );
      this.media_max_duration = this.media_init_duration;
      this.media_stop_duration = 0;
      this.media_real_duration = 0;
      clearInterval(this.timer);
    },
    videoErrorCallback() {
      uni.showToast({
        title: "暂不支持播放",
        learningDuration: 2000,
        icon: "none",
      });
    },
    isNoComplete({ coursewareStatus }) {
      return Number(coursewareStatus) < 3;
    },
    isStudying({ coursewareStatus }) {
      return Number(coursewareStatus) === 2;
    },
    isCurrentSelect({ coursewareHistoryId }) {
      return get(this.currentCourse, "coursewareHistoryId") === coursewareHistoryId;
    },
    formatStatus(status, key) {
      return get(statusMap, `${status || 1}.${key}`);
    },
    handleTime(e) {
      console.log('handleTime handleTime')
      if (this.currentCourse.coursewareStatus == "3") {
        return;
      }

      let media_jump_duration;
      const currentTime = Number(e.detail.currentTime);
      this.currentDuration = Math.floor(e.detail.learningDuration);
      if (!this.media_real_duration) {
        media_jump_duration =
          Number(this.media_init_duration) + Number(this.media_real_duration);
      } else {
        media_jump_duration = Number(this.media_max_duration);
      }

      if (
        this.isNoComplete(this.currentCourse) &&
        currentTime > media_jump_duration &&
        currentTime - media_jump_duration > 1
      ) {
        const videoContext = uni.createVideoContext("myVideo");
        videoContext.seek(Math.floor(this.media_real_duration));
        uni.showToast({
          title: "未完整看完该视频, 不能快进",
          learningDuration: 2000,
          icon: "none",
        });
        return;
      }
      this.media_real_duration = currentTime;
      if (this.media_real_duration > this.media_max_duration) {
        this.media_max_duration = this.media_real_duration;
      }

      if (this.currentCourse.learningDuration - this.media_real_duration < 0.2) {
        this.currentCourse.coursewareStatus = "2";
        this.saveTime();
        this.toNextCourse();
      }
    },
    handleComplete() {
      this.startTime();
    },
    startTime() {
      if (this.currentCourse.coursewareStatus !== "3") {
        this.currentCourse.coursewareStatus = "2";
        this.timeCount = 0;
        clearInterval(this.timeCountTimer);
        this.timeCountTimer = setInterval(() => {
          ++this.timeCount;

          if (
            this.currentCourse.trainLearnedDuration + this.timeCount >=
            this.currentCourse.learningDuration
          ) {
            this.saveTime();
            clearInterval(this.timeCountTimer);
            this.toNextCourse();
          }
        }, 1000);
      }
    },
    async toNextCourse() {
      const coursewareLists = this.detailData.coursewareLists;
      for (var i = 0; i < coursewareLists.length; i++) {
        if (
          coursewareLists[i].coursewareHistoryId === this.currentCourse.coursewareHistoryId
        ) {
          coursewareLists[i].coursewareStatus = "3";
          if (coursewareLists[i + 1].coursewareHistoryId) {
            // // 将下一条数据解锁,修改下一条状态
            await postCourseLearnedTime(this.planId, {
              id: get(coursewareLists[i + 1], "id", ""),
              learnedDuration: get(
                coursewareLists[i + 1],
                "trainLearnedDuration",
                0
              ) || 0
            });
            coursewareLists[i + 1].coursewareStatus = "2";
            break;
          }
        }
      }
      this.detailData.coursewareLists = coursewareLists;
    },
    saveTime() {
      clearInterval(this.timeCountTimer);
      if (
        this.currentCourse &&
        this.currentCourse.coursewareStatus !== "3" &&
        this.currentCourse.coursewareHistoryId
      ) {
        let learnedDuration = "";
        let coursewareStatus = "";
        if (this.currentCourse.fileType == "8") {
          learnedDuration =
            this.currentCourse.learningDuration - this.media_real_duration < 3
              ? this.currentCourse.learningDuration
              : this.media_real_duration;
          coursewareStatus =
            this.currentCourse.learningDuration - this.media_real_duration < 3
              ? "3"
              : "2";
        } else {
          learnedDuration =
            this.currentCourse.trainLearnedDuration + this.timeCount >=
            this.currentCourse.learningDuration
              ? this.currentCourse.learningDuration
              : this.currentCourse.trainLearnedDuration + this.timeCount;
          coursewareStatus =
            this.currentCourse.trainLearnedDuration + this.timeCount >=
            this.currentCourse.learningDuration
              ? "3"
              : "2";
        }

        let param = {
          id: get(this.currentCourse, "id", ""),
          learnedDuration
        }
        console.log('save param', param)
        postCourseLearnedTime(this.planId, {
          id: get(this.currentCourse, "id", ""),
          learnedDuration
        }).then((result) => {
          getTrainingCourse(this.planId).then((res) => {
            res.data.coursewareLists = res.data.coursewareList
            let detail = get(res, "data");

            this.currentCourse.trainLearnedDuration = learnedDuration;
            this.timeCount = 0;
            let newCurrentCourse = find(
              detail.coursewareLists,
              (item) => item.coursewareHistoryId === this.currentCourse.coursewareHistoryId
            );

            //只更新当前播放的数据
            this.detailData.coursewareLists.forEach((item) => {
              if (item.coursewareHistoryId === newCurrentCourse.coursewareHistoryId) {
                item.trainLearnedDuration =
                  newCurrentCourse.trainLearnedDuration;
                item.trainLearnedDurationLabel =
                  newCurrentCourse.trainLearnedDurationLabel;
              }
            });
            // this.currentCourse = newCurrentCourse;

            if (detail.evaluateFlag === "Y") {
              let noCompleteList = find(detail.coursewareLists, (item) =>
                this.isNoComplete(item)
              );
              if (!noCompleteList) {
                this.dialogVisible = true;
              }
            }
          });
        });
      }
    },
    async handlePlay() {
      //this.startTime();
      if (!this.media_max_duration) {
        this.currentCourse.coursewareStatus = "2";
      }
      if (this.currentCourse.coursewareStatus !== "3") {
        clearInterval(this.timer);
        this.media_stop_duration = 0;
        this.timer = setInterval(() => {
          this.media_stop_duration++;
          if (this.media_stop_duration >= 60 * 5) {
            clearInterval(this.timer);
            this.media_stop_duration = 0;
            const videoContext = uni.createVideoContext("myVideo");
            videoContext.pause();
            uni.showModal({
              title: "系统提示",
              content: "您是否正在学习中?",
              showCancel: false,
              success: () => {
                videoContext.play();
              },
            });
          }
        }, 1000);
      }
    },
    handlePause() {
      // this.saveDuration(2, this.media_max_duration)
      this.saveTime();
      clearInterval(this.timer);
    },
    handleEnded() {
      clearInterval(this.timer);
      // this.saveDuration(3, this.currentDuration)
      // this.saveTime()
      // this.toNextCourse()
    },
    initCourse() {
      const coursewareLists = get(this.detailData, "coursewareLists", []);
      const noCompleteList = find(coursewareLists, (item) =>
        this.isNoComplete(item)
      );
      this.currentCourse = noCompleteList ? noCompleteList : coursewareLists[0];
    },
    handleChangeCourse(item) {
      // 视频
      if (item.fileType === "8") {
        // 点击同一个视频
        if (item.coursewareHistoryId === this.currentCourse.coursewareHistoryId) {
          return;
        }
        // 学习状态为学习中,已完成
        if (item.coursewareStatus !== "1") {
          this.currentCourse = item;
          this.initTimeAttr();
        }
      } else {
        // 文件
        // 学习状态为学习中,已完成 进入文件预览开始计时,离开页面保存时
        // if (item.coursewareStatus !== '1') {
        this.currentCourse = item;
        this.initTimeAttr();
        uni.navigateTo({
          url:
            "/pages/work/training-tasks/file-preview?url=" +
            encodeURIComponent(item.fileUrl),
          events: {
            saveTime: () => {
              console.log('777')
              this.saveTime();
            },
            startTime: () => {
              this.startTime();
            },
          },
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.media-box .video {
  width: 100%;
  height: 450rpx;
}

.text-bold {
  font-size: 36rpx;
}

.mt-14 {
  margin-top: 14rpx;
}

.text-gray {
  font-size: 24rpx;
  color: #9b9fac;
}

.bg-studying {
  background: #ebf2f5;
}

.box-content {
  position: relative;
  height: 195rpx;

  image {
    width: 78rpx;
    height: 78rpx;
    flex-shrink: 0;
  }

  .title {
    font-size: 30rpx;
    word-break: break-all;
  }

  .time {
    padding-left: 28rpx;
    margin-top: 4rpx;
  }

  .status {
    position: absolute;
    bottom: 15rpx;
    right: 30rpx;
  }

  .progress {
    left: 0;
    position: absolute;
    width: 100%;
    bottom: 0;
  }
}
</style>
